    //
//  SelectSchoolController.m
//  EducationAdminClient
//
//  Created by KWSD on 15/12/5.
//  Copyright © 2015年 周佳兴. All rights reserved.
//

#import "SelectSchoolController.h"
#import "SchoolDetailController.h"
#import "SchoolsCell.h"
#import "SearchView.h"
#import "SearchViewController.h"

@interface SelectSchoolController (){
    UIView *vHead;
}
@property(nonatomic,retain)NSMutableArray       *fieldArr;
@property(nonatomic,retain)NSMutableArray       *titleArr;
@property(nonatomic,retain)NSMutableArray       *totlearr;

@property(nonatomic,strong)SearchView           *searchView;
@property(nonatomic,strong)UIImageView          *trangle2;
@property(nonatomic,strong)UIImageView          *backImg;
@property(nonatomic,strong)NSMutableArray       *btnArr;
@property(nonatomic,strong)NSIndexPath          *lastIndexPath;
@property(nonatomic,strong)UIButton             *lastButton;


@end

@implementation SelectSchoolController
static const CGFloat MJDuration = 0.5;

static int begin = 0;
static int limit = 20;

- (void)viewDidLoad {
    [super viewDidLoad];
    _flag = YES;
    // Do any additional setup after loading the view.
    _fieldArr = [[NSMutableArray alloc]init];
    _titleArr = [[NSMutableArray alloc]init];
     _numArr = [[NSMutableArray alloc]init];
    _totlearr = [[NSMutableArray alloc]init];
//    [self dataRequest];
    [self createLeftNavBar];
    [self createRightNavBar];
    
    self.tbView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tbView];
    self.tbView.dataSource = self;
    self.tbView.delegate = self;
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    if(!self.treeDir){
        self.tbView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self footerRefresh];
        }];
    }
    
    [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
    
    _searchView = [[SearchView alloc]init];
    [self.view addSubview:_searchView];
    _searchView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
    _searchView.hidden = YES;
    [_searchView.bottom addTarget:self action:@selector(buttomClick:) forControlEvents:UIControlEventTouchUpInside];
    [_searchView.backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    _backImg =[[UIImageView alloc]init];
    [self.view addSubview:_backImg];
    _backImg.frame = CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    _backImg.backgroundColor =[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view bringSubviewToFront:_searchView];
    _backImg.hidden = YES;
    _btnArr = [[NSMutableArray alloc]init];
        NSLog(@"%@",_btnArr);
    _backImg.userInteractionEnabled = YES;
    UISwipeGestureRecognizer *swip =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipClick:)];
    swip.direction = UISwipeGestureRecognizerDirectionUp;
    [_backImg addGestureRecognizer:swip];

}


-(void)swipClick:(UISwipeGestureRecognizer *)swip{
    
    [UIView animateWithDuration:0.2 animations:^{
        _searchView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
    }];
//    flag = YES;
    _backImg.hidden = YES;
    self.tbView.userInteractionEnabled = YES;
    [_searchView endAnima];
    
}
-(void)footerRefresh{
    [self.tbView.footer beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        begin += limit;
        [self dataRequestWithBegining:begin andLimit:limit andIsFooter:YES];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.footer endRefreshing];
    });
    
}

-(void)dataRequestWithBegining:(int)begin andLimit:(int)limit andIsFooter:(BOOL)is{
    NSMutableDictionary *_param = [[NSMutableDictionary alloc]init];
    [_param setObject:[NSString stringWithFormat:@"%i", limit] forKey:@"limit"];
    [_param setObject:[NSString stringWithFormat:@"%i", begin] forKey:@"start"];
    if(self.pageId){
     [_param setObject:self.pageId forKey:@"pageId"];
    }
    if(self.tableId){
     [_param setObject:self.tableId forKey:@"tableId"];
    }
    [_param setObject: getSessionId() forKey:@"sessionId"];
    
    NSString *requestStr;// = self.searchUrl;
//    if(self.premiseKey){
//    
//        [_param setObject:self.premise forKey:self.premiseKey];
//        
//    }
    [_param setValuesForKeysWithDictionary:self.premiseDic];
    if(self.treeDir){
        requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, TREEDIALOG_URL];
    }else{
        requestStr = self.searchUrl;
    }
    
    [NetRequest requestUrl:requestStr andParamas:_param andReturnBlock:^(NSData *data, NSError *error) {
        if(!error&&data!=nil){
            NSLog(@"%@",data);
            id d =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            
//            if ([d valueForKey: @"promptMessage"]) {
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
//                
//            }
            //下拉树暂时去掉系统超时
            NSMutableArray *currwntDataArr;
            if([d isKindOfClass:[NSArray class]]){
            
             currwntDataArr = [NSMutableArray arrayWithArray:d];

            }else{
                currwntDataArr = [d valueForKey:@"dataList"];
                self.searchArr = [[d valueForKey:@"pageSet"] valueForKey:@"serachSet"];
            }
            NSLog(@"%@",d);
            if (is) {
                for (id obj in currwntDataArr) {
                    [_schoolArr addObject:obj];
                    for (int i=0; i<_schoolArr.count; i++) {
                        NSDictionary *dic =[_schoolArr objectAtIndex:i];
                        [_btnArr addObject:@"0"];
                        for(NSString *str in _firstPageArr){
                            if([str isEqualToString:[NSString stringWithFormat:@"%@", [dic objectForKey:@"AFM_1"]]]){
                                [_btnArr replaceObjectAtIndex:i withObject:@"1"];
                                
                                [_titleArr addObject:[dic objectForKey:@"AFM_1"]];
                                [_numArr addObject:[dic objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
                                


                            }else if([str isEqualToString:[NSString stringWithFormat:@"%@", [dic objectForKey:@"name"]]]){
                                [_btnArr replaceObjectAtIndex:i withObject:@"1"];
                                
                                [_titleArr addObject:[dic objectForKey:@"name"]];
                                [_numArr addObject:[dic objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
                                
                                
                                
                            }

                        }
                    }

                    [self.tbView reloadData];
                }
            }else{
                _schoolArr = [NSMutableArray arrayWithArray:currwntDataArr];
                [self.tbView reloadData];
                for (int i=0; i<_schoolArr.count; i++) {
                    NSDictionary *dic =[_schoolArr objectAtIndex:i];
                    [_btnArr addObject:@"0"];
                    for(NSString *str in _firstPageArr){
                        if([str isEqualToString:[dic objectForKey:@"AFM_1"]]){
                            [_btnArr replaceObjectAtIndex:i withObject:@"1"];
                            
                            [_titleArr addObject:[dic objectForKey:@"AFM_1"]];
                            [_numArr addObject:[dic objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];

                        }
                    }
                }

            }
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];

        }
    }];

    
}

-(void)dataRequest{
    NSArray *arr = [_searchUrl componentsSeparatedByString:@"?"];
    NSString *requestStr =@"";
    NSArray *arr2 = [arr[1] componentsSeparatedByString:@"&"];
    NSArray *array1 = [arr2[0] componentsSeparatedByString:@"="];
    NSArray *array2 = [arr2[1] componentsSeparatedByString:@"="];
    NSMutableDictionary *_param = [[NSMutableDictionary alloc]init];
    [_param setObject:array1[1] forKey:array1[0]];
    [_param setObject:array2[1] forKey:array2[0]];
    requestStr =arr[0];
    [NetRequest requestUrl:requestStr andParamas:_param andReturnBlock:^(NSData *data, NSError *error) {
        if(!error&&data!=nil){
            NSLog(@"%@",data);
            NSDictionary *d =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",d);
            _fieldArr  =[d objectForKey:@"rows"];
            [self.tbView reloadData];
            
        }else{
            
            //            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            
            
        }
    }];

}

#pragma mark - create right nav bar btn
-(void)createRightNavBar{
    UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightNavBtn.frame = CGRectMake(0, 0, 50, 23);
    [rightNavBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [rightNavBtn addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    //    self.navigationItem.leftBarButtonItem = item;
    [rightNavBtn setTitle:@"提交" forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = item;

//    self.editBtn = rightNavBtn;
}

-(void)buttomClick:(UIButton *)btn{
    
    [UIView animateWithDuration:0.2 animations:^{
        _searchView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
    }];
    self.tbView.userInteractionEnabled = YES;
    [_searchView endAnima];
    _flag = YES;
    _backImg.hidden = YES;
}

-(void)rightClick:(UIButton *)btn{
    NSMutableDictionary *titleDic = [[NSMutableDictionary alloc]init];
    for(NSString *str in _titleArr){
        [titleDic setObject:str forKey:str];
    }
    NSMutableDictionary *numDic = [[NSMutableDictionary alloc]init];
    for(NSString *numstr in _numArr){
        [numDic setObject:numstr forKey:numstr];
    }
    
   
//    [_totlearr addObject:_titleArr];
//    [_totlearr addObject:_numArr];
    [_totlearr addObject:[titleDic allKeys]];
     [_totlearr addObject:[numDic allKeys]];
    if(_totlearr.count>=2){ // _titleArr.count&&
        if(_numArr.count){
//            [[NSNotificationCenter defaultCenter]postNotificationName:@"schools" object:_totlearr];
        }else{
//            if(_titleArr.count>=2)[[NSNotificationCenter defaultCenter]postNotificationName:@"schools" object:_titleArr];
        }
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"schools" object:_totlearr];
        
        if (self.delegateView) {
            [self.delegateView performSelector:@selector(receiveSeleData:) withObject:_totlearr];
        }

        
    }
    
            [self.navigationController popViewControllerAnimated:YES];
}

-(void)recrviveData:(NSNotification *)n{
    
    NSArray *arr = [n object];
    _schoolArr = [NSMutableArray arrayWithArray:arr];
    [self.tbView reloadData];
}

-(void)LeftClick:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _schoolArr.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"identifier";
    SchoolsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell==nil){
        
         cell =[[SchoolsCell alloc]initWithReuseIdentifier:str];
    }
    
    cell.one = self.one;
    
    NSDictionary *dic = [_schoolArr objectAtIndex:indexPath.row];
    NSArray *arr = [dic allKeys];
    arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result==NSOrderedDescending;
    }];

//    NSDictionary *fieldDic = [_fieldArr objectAtIndex:indexPath.row];
    NSString  *dicStr =[dic objectForKey:@"name"];
    if(dicStr.length!=0){
    cell.titleName.text = [dic objectForKey:@"name"];
    }else if([dic objectForKey:@"AFM_1"]){
        cell.titleName.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"AFM_1"]];
    }else if(arr.count>0){
        if([arr containsObject:@"USERNAME"]){
            cell.titleName.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"USERNAME"]];
        }else{
         cell.titleName.text = [NSString stringWithFormat:@"%@", [dic objectForKey:arr[0]]];
        }
        
    }
    else{
        NSString *nameStr= [NSString stringWithFormat:@"F_%@_AFM_1",_schoolFieldStr];
        cell.titleName.text = [dic objectForKey:nameStr];
    }
    cell.object = self;
    cell.indexPath = indexPath;
    cell.schoolSelector = @selector(schoolSelectClick:);
    cell.seleBtn.tag = 1000+indexPath.row;
    if(_btnArr.count){
    BOOL aa = [[_btnArr objectAtIndex:indexPath.row] boolValue];
    if(aa){
        cell.seleBtn.selected = YES;
    }
    else{
         cell.seleBtn.selected = NO;
    }
    }
   

   
    return cell;
    
}

-(void)schoolSelectClick:(NSIndexPath *)indexPath{
    
    if(self.one&&_lastIndexPath!=nil&&_lastButton){   // if one
        
        
       
        

        NSDictionary *oneItem = [_schoolArr objectAtIndex:_lastIndexPath.row];
        NSString  *dicStr =[oneItem objectForKey:@"name"];

        if(dicStr.length!=0){  // if two
           
                [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
                [_titleArr removeObject:dicStr];
                [_numArr removeObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
                [_lastButton setImage:[UIImage imageNamed:@"椭圆-1-拷贝-3"] forState:UIControlStateNormal];
                _lastButton.selected = NO;

            
        }
        
        //
        else{
            
                [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
            
                NSString *nameStr= [NSString stringWithFormat:@"AFM_1"];
                [_titleArr removeObject:[oneItem objectForKey:nameStr]];
                [_numArr removeObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
                _lastButton.selected = NO;

            
        }  // if two end

    }   // if one end
    
    
    //*** more select
    UIButton *btn =(UIButton *)[self.view viewWithTag:1000+indexPath.row];
    
    _lastButton = btn;
    _lastIndexPath = indexPath;
    
    NSDictionary *oneItem = [_schoolArr objectAtIndex:indexPath.row];
     NSString  *dicStr =[oneItem objectForKey:@"name"];
    if(dicStr.length!=0){
    if(!btn.selected){
        [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
        [_titleArr addObject:dicStr];
        [_numArr addObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
    }
    else{
         [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
        [_titleArr removeObject:dicStr];
        [_numArr removeObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
    }
    }
    
    // 
    else{
        
        NSArray *arr = [oneItem allKeys];
        arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            NSComparisonResult result = [obj1 compare:obj2];
            return result==NSOrderedDescending;
        }];

        if(!btn.selected){
             [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
//            NSString *nameStr= [NSString stringWithFormat:@"F_%@_AFM_1",_schoolFieldStr];

            NSString *nameStr= [NSString stringWithFormat:@"%@", arr[0]];
            if([arr containsObject:@"USERNAME"]){
               [_titleArr addObject:[oneItem objectForKey:@"USERNAME"]];
            }else{
              [_titleArr addObject:[oneItem objectForKey:nameStr]];
            }
            
            [_numArr addObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
        }
        else{
            [_btnArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
//            NSString *nameStr= [NSString stringWithFormat:@"F_%@_AFM_1",_schoolFieldStr];

            NSString *nameStr= [NSString stringWithFormat:@"%@", arr[0]];
            [_titleArr removeObject:[oneItem objectForKey:nameStr]];
            [_numArr removeObject:[oneItem objectForKey:[NSString stringWithFormat:@"T_%@_0",_schoolFieldStr]]];
        }
       
        
  
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    SchoolDetailController *sv = [[SchoolDetailController alloc]init];
//    [self.navigationController pushViewController:sv animated:YES];
////    sv.fieldArr = _schoolFieldStr;
//    sv.itemDic =[_schoolArr objectAtIndex:indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    vHead =[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
    vHead.backgroundColor =[UIColor yellowColor];
    
    //*** shaixuan btn
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    
    
    
    [vHead addSubview:searchBtn];
    searchBtn.backgroundColor =[UIColor whiteColor];
    
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(vHead.mas_left);
        
        make.top.equalTo(vHead.mas_top);
        make.right.equalTo(vHead.mas_right);
        make.height.equalTo(@(86/2));
    }];
    //    [searchBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"搜索_"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"搜索点击状态_"] forState:UIControlStateHighlighted];
    
    [searchBtn addTarget:self action:@selector(searchClick:) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateNormal];
    searchBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    
    return vHead;
    
}

-(void)allClick:(UIButton *)btn{
    
}

-(void)searchClick:(UIButton *)btn{
    
    SearchViewController *searchVC = [[SearchViewController alloc]initWithBlock:^(NSDictionary *dic) {
    
    }];
    searchVC.delegate = self;
    searchVC.dataArr = _searchArr;
    searchVC.pageID = _pageId;
    searchVC.tableID = _tableId;
    searchVC.searchUrl = _searchUrl;

    
    [self presentViewController:searchVC animated:YES completion:^{
        
    }];
    
}


-(void)backClick:(UIButton *)Btn{
    [UIView animateWithDuration:0.2 animations:^{
        _searchView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0);
    }];
     self.tbView.userInteractionEnabled = YES;
    [_searchView endAnima];
    _flag = YES;
    _backImg.hidden = YES;
  
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(recrviveData:) name:@"row" object:nil];

}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    

    begin=0;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"row" object:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
